import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:go_router/go_router.dart';
import 'package:zywz/generated/assets.dart';

import '../../api/api_client.dart';
import '../../bloc/report/report_bloc.dart';
import '../../bloc/report/report_data.dart';
import '../../bloc/report/report_event.dart';
import '../../dialog/showBtm.dart';


class TaxReport  extends StatelessWidget {
  const TaxReport({super.key});

  @override
  Widget build(BuildContext context) {
    return BlocProvider<ReportBloc>(
      create: (context) => ReportBloc(apiClient: ApiClient.instance),
      child: MaterialApp(
        debugShowCheckedModeBanner: false,
        theme: ThemeData(
          scaffoldBackgroundColor: const Color(0xFFF7F9FC), // 背景色
          appBarTheme: const AppBarTheme(
            backgroundColor: Colors.white,
            elevation: 0,
            centerTitle: true,
            titleTextStyle: TextStyle(
              color: Colors.black,
              fontSize: 18,
              fontWeight: FontWeight.bold,
            ),
          ),
        ),
        home: const TaxReportPage(),
      ),
    );
  }
}

// 纳税列表项数据模型
class TaxItem {
  final String title;
  final Color color;
  final double value;

  const TaxItem({
    required this.title,
    required this.color,
    this.value = 0.00,
  });
}

class TaxReportPage extends StatefulWidget {
  const TaxReportPage({super.key});

  @override
  State<TaxReportPage> createState() => _TaxReportPageState();
}

class _TaxReportPageState extends State<TaxReportPage> {
  // 模拟纳税项目数据
  final List<TaxItem> taxItems = const [
    TaxItem(title: '增值税:', color: Colors.red),
    TaxItem(title: '印花税:', color: Colors.pink),
    TaxItem(title: '城建税:', color: Color(0xFFE470C0)),
    TaxItem(title: '教育费附加:', color: Color(0xFF90C2F2)),
    TaxItem(title: '地方教育费附加:', color: Color(0xFFA1E094)),
    TaxItem(title: '企业所得税:', color: Color(0xFFF99D43)),
  ];




  int getCurrentQuarter() {
    final now = DateTime.now();
    return (now.month - 1) ~/ 3 + 1;
  }

  // 或者更详细的方法
  String getCurrentQuarterString() {
    final now = DateTime.now();
    final quarter = (now.month - 1) ~/ 3 + 1;
    switch (quarter) {
      case 1:
        return '第一季度';
      case 2:
        return '第二季度';
      case 3:
        return '第三季度';
      case 4:
        return '第四季度';
      default:
        return '第一季度'; // 默认值
    }
  }
  // 或者更详细的方法
  String getCurrentJd(int caseOp) {
    switch (caseOp) {
      case 1:
        return '第一季度';
      case 2:
        return '第二季度';
      case 3:
        return '第三季度';
      case 4:
        return '第四季度';
      default:
        return '第一季度'; // 默认值
    }
  }


  var jidu = '第一季度';
  var jiduIndex = 0;
  var yearIndex = 0;
  var titleShow ="(2025) 第一季度";

  final List<String> jiduStart = ['01', '03', '06', '09'];
  final List<String> jiduEnd = ['03', '06', '09', '12'];

  @override
  void initState() {
    super.initState();


    var selectedYear = DateTime.now().year;
    yearIndex = 0;
    jidu = getCurrentQuarterString();
    jiduIndex = getCurrentQuarter()-1;
    titleShow = "($selectedYear) $jidu";

    context.read<ReportBloc>().add(LoadReportData( "$selectedYear${jiduStart[jiduIndex]}", "$selectedYear${jiduEnd[jiduIndex]}"));
  }


  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        leading: IconButton(
          icon: const Icon(Icons.arrow_back_ios, color: Colors.black, size: 20),
          onPressed: () {
            // 返回上一页的逻辑
            context.pop();
            // context.push('/WheelPickerExample');
          },
        ),
        title: const Text('纳税表'),
      ),
      body: Column(
        children: [
          // 时间选择器区域
          _buildTimeSelector(context),
          const SizedBox(height: 10),
          // 纳税查看Banner
          _buildBanner(context),
          const SizedBox(height: 10),
          // 纳税列表
          _buildTaxList(),
        ],
      ),
    );
  }

  // 构建时间选择器
  Widget _buildTimeSelector(BuildContext context) {
    return Container(
      padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
      alignment: Alignment.center,
      child: GestureDetector(
        onTap: () async {
        var dataMap= await  showSlectSheet1(
            context,
            indexYear: yearIndex,
            jiduItem: jiduIndex,
            callBack: (year, jidu) {
              print('$year $jidu');
              var selectedYear = DateTime.now().year;
              setState(() {
                yearIndex = year;
                jiduIndex = jidu;

                titleShow = "(${selectedYear - year}) ${getCurrentJd(jidu+1)}";
              });

              context.read<ReportBloc>().add(LoadReportData( "${selectedYear - yearIndex}${jiduStart[jiduIndex]}", "${selectedYear - yearIndex}${jiduEnd[jiduIndex]}"));

            },
          );

        print("dataMap $dataMap");

          // showBottomSheet(
          //   context,
          //   title: '选择时间',
          //   items: ['2025年第一季度', '2025年第二季度', '2025年第三季度', '2025年第四季度'],
          //   onTap: (index) {
          //     // 处理选择的时间
          //   },
          // );
        },
        child: Row(
          mainAxisSize: MainAxisSize.min,
          children: [
            Text(
              titleShow,
              style: const TextStyle(
                fontSize: 14,
                fontWeight: FontWeight.bold,
              ),
            ),
            const Icon(Icons.arrow_drop_down),
          ],
        ),
      ),
    );
  }

  // 构建纳税查看Banner
  Widget _buildBanner(BuildContext context) {
    return Container(
      margin: const EdgeInsets.symmetric(horizontal: 16.0),
      height: 140,
      decoration: BoxDecoration(
        borderRadius: BorderRadius.circular(12),
        gradient: const LinearGradient(
          colors: [Color(0xFF8AD1FF), Color(0xFF5DD9FF)],
          begin: Alignment.topLeft,
          end: Alignment.bottomRight,
        ),
        boxShadow: [
          BoxShadow(
            color: const Color(0xFF5DD9FF).withOpacity(0.3),
            spreadRadius: 1,
            blurRadius: 10,
            offset: const Offset(0, 5),
          ),
        ],
      ),
      child: Stack(
        children: [
          // Banner背景图，由于无法从代码中创建，这里用一个占位图来模拟
          // 在实际项目中，你可以将设计稿中的装饰图保存为PNG或SVG，并放在assets文件夹中
          // Image.asset('assets/tax_banner_bg.png'),
          Positioned(
            left: 20,
            bottom: 20,
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                const Text(
                  '纳税查看器',
                  style: TextStyle(
                    fontSize: 24,
                    fontWeight: FontWeight.bold,
                    color: Colors.white,
                  ),
                ),
                const SizedBox(height: 5),
                Container(
                  padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 4),
                  decoration: BoxDecoration(
                    color: Colors.white.withOpacity(0.3),
                    borderRadius: BorderRadius.circular(12),
                  ),
                  child: Row(
                    children: const [
                      Icon(Icons.search, color: Colors.white, size: 16),
                      SizedBox(width: 4),
                      Text('纳税查看', style: TextStyle(color: Colors.white, fontSize: 12)),
                    ],
                  ),
                ),
              ],
            ),
          ),
          // 模拟右侧的装饰图
          Positioned(
            right: 0,
            top: 0,
            bottom: 0,
            child: Opacity(
              opacity: 0.5,
              child:Image.asset(Assets.iconIconQyXg,
                fit: BoxFit.fill,
              ),
            ),
          ),
        ],
      ),
    );
  }

  // 构建纳税列表
  Widget _buildTaxList() {
    return BlocConsumer<ReportBloc, ReportState>(
        buildWhen: (previous, current) {
          if (current is ReportTaxReportSuccess) {
            return true;
          }
          return false;
        },
        listener: (context, state) {
          if (state is ReportLoadFailure) {

          }
        },
        builder: (context, state) {
          if (state is ReportTaxReportSuccess) {
            return Container(
              margin: const EdgeInsets.symmetric(horizontal: 16.0),
              padding: const EdgeInsets.all(16.0),
              decoration: BoxDecoration(
                color: Colors.white,
                borderRadius: BorderRadius.circular(12),
                boxShadow: [
                  BoxShadow(
                    color: Colors.grey.withOpacity(0.1),
                    spreadRadius: 1,
                    blurRadius: 5,
                    offset: const Offset(0, 3),
                  ),
                ],
              ),
              child: Column(
                // children: taxItems.map((item) => TaxListItem(item: item)).toList(),
                // children:[...(state.map((item) => TaxListItem(keyItem: '1', valueItem: '2')).toList())],
                children: state.reportData.entries.map((entry) =>
                    TaxListItemX(
                        keyItem: entry.key,
                        valueItem: entry.value?.toString() ?? ''
                    )).toList(), // 注意这里需要 toList()
                // children: [],
              ),
            );
          } else {
            return Container();
          }
        });
  }

  //   return BlocSelector<ReportBloc,ReportState,Map<String,dynamic>>(
  //     selector: (state) {
  //       if(state is ReportTaxReportSuccess){
  //         return state.reportData;
  //       }
  //       return {};
  //     },
  //     builder: (BuildContext context, Map<String, dynamic> state) {
  //         return ;
  //     }
  //   );
  // }
}




var mapClose = {
  '增值税': Colors.red,
  '印花税': Colors.pink,
  '城建税': Color(0xFFE470C0),
  '教育费附加': Color(0xFF90C2F2),
  '地方教育费附加': Color(0xFFA1E094),
  '企业所得税': Color(0xFFF99D43),
};

// 可复用的列表项组件
class TaxListItemX extends StatelessWidget {
  final String keyItem;
  final String valueItem;

  const TaxListItemX({super.key, required this.keyItem, required this.valueItem});

  @override
  Widget build(BuildContext context) {
    return Padding(
      padding: const EdgeInsets.symmetric(vertical: 10.0),
      child: Row(
        children: [
          Container(
            width: 12,
            height: 12,
            decoration: BoxDecoration(
              color: mapClose[keyItem] ?? Color(0xFF90C2F2),
              borderRadius: BorderRadius.circular(2),
            ),
          ),
          const SizedBox(width: 10),
          Text(
            keyItem??'',
            style: const TextStyle(fontSize: 16, color: Color(0xFF4A4A4A)),
          ),
          const Spacer(),
          Text(
            valueItem ?? '',
            style: const TextStyle(
              fontSize: 16,
              fontWeight: FontWeight.bold,
              color: Color(0xFF4A4A4A),
            ),
          ),
        ],
      ),
    );
  }
}